<!-- goodInfo.vue -->
<template>
  <!-- 头部区域 -->
  <StoreHeader></StoreHeader>
  <div class="product-detail">
    <!-- 商品主体内容 -->
    <el-row :gutter="20" class="main-content">
      <!-- 左侧商品图片区域 -->
      <el-col :span="10">
    <div class="product-images">
      <div class="main-image-container">
        <el-carousel height="400px" indicator-position="outside" arrow="always"
          @change="handleCarouselChange">
          <el-carousel-item v-for="(image, index) in product.images" :key="index">
            <el-image 
              :src="image" 
              class="carousel-image" 
              fit="contain"
              :preview-src-list="product.images" 
              :initial-index="index"
              style="width: 100%; height: 100%;"
            >
              <template #placeholder>
                <div class="image-slot">
                  <el-icon>
                    <Picture />
                  </el-icon>
                </div>
              </template>
              <template #error>
                <div class="image-slot">
                  <el-icon>
                    <Picture />
                  </el-icon>
                </div>
              </template>
            </el-image>
          </el-carousel-item>
        </el-carousel>
      </div>
    </div>
  </el-col>

      <!-- 右侧商品信息区域 -->
      <el-col :span="14">
        <div class="product-info">
          <!-- 商品标题 -->
          <div class="product-title">
            <h1>{{ product.title }}</h1>
            <p class="subtitle" v-if="product.subtitle">{{ product.subtitle }}</p>
          </div>

          <!-- 价格信息 -->
          <div class="price-section">
            <div class="price-row">
              <span class="price-label">价格</span>
              <span class="price-current">¥{{ product.price }}</span>
            </div>

            <div class="sales-info">
              <span>
                <el-icon>
                  <Location />
                </el-icon>交易地点：{{product.universityName}} {{ product.dealLocation }}
              </span>
            </div>
          </div>
          
          <!-- 商品类型说明 -->
          <div class="product-type-section">
            <div class="type-item">
              <span class="type-label">商品类型：</span>
              <el-tag type="success" size="small">{{ product.productType }}</el-tag>
            </div>
            <div class="type-item">
              <span class="type-label">新旧程度：</span>
              <el-tag type="primary" size="small">{{ product.oldAndNew }}</el-tag>
            </div>
            <div class="type-item">
              <span class="type-label">适用人群：</span>
              <el-tag type="warning" size="small">{{ product.applicablePeople }}</el-tag>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="action-buttons">
            <el-button type="danger" size="large" class="btn-add-cart" @click="reportDialogVisible = true">
              <el-icon>
                <Aim />
              </el-icon>
              商品举报
            </el-button>
            <el-button type="warning" size="large" class="btn-add-cart">
              <el-icon>
                <ChatDotRound />
              </el-icon>
              卖家联系
            </el-button>
            <el-button type="success" size="large" @click="buyNow" class="btn-buy-now">
              <el-icon>
                <ShoppingCart />
              </el-icon>
              立即购买
            </el-button>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 商品详情区域 -->
  <div class="detail-section">
    <el-tabs v-model="activeDetailTab" class="detail-tabs">
      <el-tab-pane label="卖家评价" name="comments" style="padding-left: 15px;">
        <div class="comments-container" ref="commentsContainerRef" @scroll="handleScroll">
          <!-- 评价统计 -->
          <div class="comment-summary">
            <div class="summary-score">
              <span class="score">{{ product.sellerScore }}</span>
              <span class="score-text">卖家信誉分数</span>
            </div>
            <div class="summary-detail">
              <div class="comment-count">用户评论 {{ sellerEvaluation.customerCommentNum }} 条</div>
            </div>
          </div>

          <!-- 评价筛选 -->
          <div class="comment-filter">
            <el-tag v-for="filter in commentFilters" :key="filter.key"
              :type="activeCommentFilter === filter.key ? 'primary' : ''"
              @click="filterComments(filter.key)" class="filter-tag">
              {{ filter.name }}
            </el-tag>
          </div>

          <!-- 评价列表 -->
          <div class="comments-list">
            <div class="comment-item" v-for="comment in displayedComments" :key="comment.id">
              <div class="comment-header">
                <el-avatar :src="comment.user.avatar" :size="40" />
                <div class="comment-user-info">
                  <div class="user-name">{{ comment.customerName }}</div>
                  <div class="comment-product">购买商品：{{ comment.productName }}</div>
                  <!-- 显示评价星级 -->
                  <div class="comment-rating">
                    <el-rate 
                      :model-value="comment.evaluationLevel" 
                      disabled 
                      :max="5"
                      :allow-half="false"
                      :show-score="false"
                      score-template="{value}">
                    </el-rate>
                  </div>
                </div>
              </div>
              <div class="comment-content">{{ comment.evaluationContent }}</div>
              <div class="comment-date">{{ comment.createDateTime }}</div>
            </div>
            
            <!-- 无评论时显示 -->
            <div v-if="!loadingMore && displayedComments.length === 0" class="no-comments">
              暂无评论数据
            </div>
          </div>

          <!-- 加载状态 -->
          <div class="load-more" v-if="loadingMore">
            <el-icon class="is-loading"><Loading /></el-icon>
            <span>加载中...</span>
          </div>

          <!-- 无更多数据提示 -->
          <div class="no-more-data" v-if="noMoreData">
            没有更多评论了
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="卖家出售" name="recommend">
        <div class="recommend-container" ref="productsContainerRef" @scroll="handleProductsScroll">
          <el-row :gutter="20">
            <el-col :span="6" v-for="item in displayedProducts" :key="item.productId"
              class="recommend-item">
              <ProductCard 
                :product="item" 
                @click="goToProduct(item.productId)">
              </ProductCard>
            </el-col>
          </el-row>

          <!-- 商品加载状态 -->
          <div class="load-more-products" v-if="productsLoadingMore">
            <el-icon class="is-loading"><Loading /></el-icon>
            <span>加载中...</span>
          </div>

          <!-- 无更多商品提示 -->
          <div class="no-more-products" v-if="noMoreProducts">
            没有更多商品了
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
  </div>
  <!-- 在模板中的适当位置添加对话框 -->
<el-dialog v-model="reportDialogVisible" title="举报商品" width="500px" :before-close="handleReportClose">
  <el-form :model="reportForm" label-width="100px">
    <el-form-item label="举报类型">
      <el-select v-model="reportForm.reason" placeholder="请选择举报原因">
        <el-option label="商品信息不实" value="虚假信息"></el-option>
        <el-option label="涉嫌欺诈" value="欺诈"></el-option>
        <el-option label="违禁品" value="违禁品"></el-option>
        <el-option label="侵犯知识产权" value="侵权"></el-option>
        <el-option label="其他" value="其他"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="详细说明">
      <el-input
        v-model="reportForm.description"
        type="textarea"
        placeholder="请详细描述举报原因"
        :rows="4"
      ></el-input>
    </el-form-item>
  </el-form>
  <template #footer>
    <span class="dialog-footer">
      <el-button @click="reportDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitReport">提交</el-button>
    </span>
  </template>
</el-dialog>
</template>

<script setup>
import { ref, reactive, nextTick, watch } from 'vue'
import {
  Picture,
  ShoppingCart,
  ChatDotRound,
  Aim,
  Location,
  Loading,
  Star
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter,useRoute } from 'vue-router'
import StoreHeader from '@/components/common/StoreHeader.vue'
import ProductCard from '@/components/common/ProductCard.vue'
import {getByPathVariable,postByData} from '@/api/common/base'
import {getProductOldLevelText} from '@/utils/DataTextMap'
import {getSellerEvaluations} from '@/api/common/evaluation'

const router = useRouter()
const route=useRoute()

// 商品数据
const product = ref({})

const sellerEvaluation=ref({
  sellerCreditScore:100,
  customerCommentNum:500,
  customerCommentContent:[]
})

// 评论筛选
const commentFilters = ref([
  { key: 'all', name: '全部' },
  { key: '5', name: '5星' },
  { key: '4', name: '4星' },
  { key: '3', name: '3星' },
  { key: '2', name: '2星' },
  { key: '1', name: '1星' },
])

// 卖家商品相关状态
const allProducts = ref([]) // 所有商品
const displayedProducts = ref([]) // 显示的商品
const productsContainerRef = ref(null) // 商品容器引用

// 商品滚动加载相关状态
const productsLoadingMore = ref(false)
const noMoreProducts = ref(false)
const currentProductPage = ref(1)
const productPageSize = ref(8) // 每页加载8个商品

// 评论数据相关状态
const comments = ref(sellerEvaluation.value.customerCommentContent)
const displayedComments = ref([])
const activeDetailTab = ref('comments')
const activeCommentFilter = ref('all')
const commentsContainerRef = ref(null)
const sellerId=ref(null)

// 滚动加载相关状态
const loadingMore = ref(false)
const noMoreData = ref(false)
const currentPage = ref(1)
const pageSize = ref(4) // 每页加载4条评论

// 方法定义
const buyNow = () => {
  ElMessageBox.confirm(
    '确认购买该商品吗？',
    '确认购买',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async() => {
    let res=await getByPathVariable('/business/create/order',product.value.id);
    if(res.code==200) setTimeout(()=>{
      let orderNum=res.data
      console.log(res)
      router.push(`/order/detail/${orderNum}`)
    },1000)
  })
}

const handleCarouselChange = (index) => {
  // 处理轮播图变化
}

const filterComments = (filter) => {
  activeCommentFilter.value = filter
  // 这里可以根据筛选条件过滤评论
  resetComments()
}

// 重置评论列表
const resetComments = () => {
  currentPage.value = 1
  noMoreData.value = false
  displayedComments.value = []
  loadComments()
}

// 加载评论
const loadComments = async () => {
  if (noMoreData.value || !sellerId.value) return
  
  loadingMore.value = true
  
  try {
    // 构建查询参数
    const queryParams = {
      sellerId: sellerId.value
    }
    
    // 如果选择了特定评价等级，则添加到查询参数中
    if (activeCommentFilter.value !== 'all') {
      queryParams.evaluationLevel = parseInt(activeCommentFilter.value)
    }
    
    const res = await getSellerEvaluations(queryParams)
    console.log('评价数据:', res)
    
    // 检查返回数据的有效性
    if (res.code === 200 && res.data && Array.isArray(res.data)) {
      // 映射返回的数据到组件需要的格式
      const mappedComments = res.data.map(item => ({
        id: item.id,
        evaluationContent: item.evaluationContent,
        evaluationLevel: item.evaluationLevel,
        customerName: item.customerName,
        productName: item.productName,
        createDateTime: item.createTime ? formatDate(item.createTime) : '',
        user: {
          avatar: '' // 如果有用户头像URL可以在这里添加
        }
      }))
      
      displayedComments.value = mappedComments
      // 更新评论数量
      sellerEvaluation.value.customerCommentNum = res.data.length
    }
    
    // 设置无更多数据状态
    noMoreData.value = true
  } catch (error) {
    console.error('获取评价数据失败:', error)
  } finally {
    loadingMore.value = false
  }
}


// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 处理滚动事件 - 评论
const handleScroll = () => {
  if (!commentsContainerRef.value || loadingMore.value || noMoreData.value) return
  
  const { scrollTop, scrollHeight, clientHeight } = commentsContainerRef.value
  const threshold = 50 // 距离底部50px时开始加载
  
  if (scrollHeight - scrollTop - clientHeight < threshold) {
    loadComments()
  }
}

// 初始化加载前4条评论
const initComments = () => {
  resetComments()
}

// 重置商品列表
const resetProducts = () => {
  currentProductPage.value = 1
  noMoreProducts.value = false
  displayedProducts.value = []
  loadProducts()
}

// 加载商品
const loadProducts = () => {
  if (noMoreProducts.value) return
  
  productsLoadingMore.value = true
  
  // 模拟异步加载
  setTimeout(() => {
    const start = (currentProductPage.value - 1) * productPageSize.value
    const end = start + productPageSize.value
    const newProducts = allProducts.value.slice(start, end)
    
    if (newProducts.length > 0) {
      displayedProducts.value = [...displayedProducts.value, ...newProducts]
      currentProductPage.value++
    } else {
      noMoreProducts.value = true
    }
    
    productsLoadingMore.value = false
  }, 500)
}

// 处理滚动事件 - 商品
const handleProductsScroll = () => {
  if (!productsContainerRef.value || productsLoadingMore.value || noMoreProducts.value) return
  
  const { scrollTop, scrollHeight, clientHeight } = productsContainerRef.value
  const threshold = 50 // 距离底部50px时开始加载
  
  if (scrollHeight - scrollTop - clientHeight < threshold) {
    loadProducts()
  }
}

const goToProduct = (id) => {
  router.push(`/product/${id}`)
}

// 添加举报对话框相关数据
const reportDialogVisible = ref(false)
const reportForm = reactive({
  reason: '',
  description: ''
})

// 打开举报对话框
const openReportDialog = () => {
  reportDialogVisible.value = true
}

// 关闭举报对话框前的处理
const handleReportClose = (done) => {
  ElMessageBox.confirm('确认关闭举报窗口吗？')
    .then(() => {
      done()
    })
    .catch(() => {
      // 用户取消关闭
    })
}

// 提交举报
const submitReport = () => {
  if (!reportForm.reason) {
    ElMessage.warning('请选择举报原因')
    return
  }
  
  if (!reportForm.description) {
    ElMessage.warning('请填写详细说明')
    return
  }
  
  // 这里可以添加实际的举报提交逻辑
  console.log('举报信息:', {
    productId: product.value.id,
    reason: reportForm.reason,
    description: reportForm.description
  })
  
  ElMessage.success('举报提交成功，我们会尽快处理')
  reportDialogVisible.value = false
  
  // 重置表单
  reportForm.reason = ''
  reportForm.description = ''
}

const initProductData = (productData) => { 
// 处理图片数组，合并主图和详细图片
    const images = []
    if (productData.productImage) {
      images.push(productData.productImage)
    }
    if (productData.productDetailImages && Array.isArray(productData.productDetailImages)) {
      images.push(...productData.productDetailImages)
    }
    sellerId.value=productData.sellerId
    
    product.value = {
      id: productData.productId || '该商品不存在',
      title: productData.productName || '该商品不存在',
      subtitle: productData.productDesc || '该商品不存在',
      price: productData.productPrice || '该商品不存在',
      dealLocation: productData.productLocation || '该商品不存在',
      universityName: productData.universityName || '该商品不存在',
      productType: productData.typeName || '该商品不存在',
      oldAndNew: getProductOldLevelText(productData.productOld) || '该商品不存在',
      applicablePeople: productData.applicablePeople || '该商品不存在',
      images: images.length > 0 ? images : [
        'https://via.placeholder.com/500x500/FF6B6B/FFFFFF?text=Image1',
        'https://via.placeholder.com/500x500/4ECDC4/FFFFFF?text=Image2'
      ],
      
    }
}

watch(
  () => route.params.id,
  async(newId, oldId) => {
    if (newId && newId !== oldId) {
      let query=route.params.id
      console.log(query)
      let res=await getByPathVariable('/business/product/info',query)
      if(res.data) {
        initProductData(res.data)
        setTimeout(async() => { 
          let sellerProducts=await getByPathVariable('/business/seller/product/list',sellerId.value  )
          allProducts.value = sellerProducts.data || []
          resetProducts() // 重置并加载商品
        }, 200)
      }
      else ElMessage.error('商品不存在')
      // 初始化评论列表
      await nextTick()
      initComments()
      
      // 获取卖家评论数据
      if (sellerId.value) {
        comments.value = []
        await loadComments()
      }
    }
  },
  { immediate: true }
)

// 初始化商品列表
const initProducts = () => {
  resetProducts()
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

/* 商品类型说明 */
.product-type-section {
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.type-item {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.type-item:last-child {
  margin-bottom: 0;
}

.type-label {
  font-size: 14px;
  color: #999;
  margin-right: 15px;
  width: 80px;
}

:deep(.type-item .el-tag) {
  margin-right: 10px;
}

/* 头部样式 */
.header {
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1000;
}

.header-container {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 20px;
}

/* Logo区域 */
.logo-area {
  flex: 0 0 auto;
}

.logo {
  height: 40px;
  width: auto;
  cursor: pointer;
}

/* 搜索区域 */
.search-area {
  flex: 1;
  max-width: 500px;
  margin-left: 30px;
}

.search-input {
  border-radius: 20px;
}

:deep(.search-input .el-input-group__append) {
  border-radius: 0 20px 20px 0;
  background-color: #409EFF;
  border-color: #409EFF;
}

:deep(.search-input .el-button) {
  color: white;
}

.product-detail {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

.main-content {
  margin-bottom: 30px;
}

/* 商品图片区域 */
.main-image-container {
  margin-bottom: 20px;
  height: 400px; /* 固定高度 */
}

:deep(.el-carousel) {
  height: 100%;
}

:deep(.el-carousel__container) {
  height: 400px; /* 与轮播图高度一致 */
}

:deep(.el-carousel__item) {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: contain; /* 保持图片比例，完整显示图片 */
}

/* 图片占位符 */
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

:deep(.image-slot .el-icon) {
  font-size: 36px;
}

/* 商品信息区域 */
.product-images {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.product-info {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.product-title h1 {
  font-size: 20px;
  color: #333;
  margin: 0 0 10px 0;
  line-height: 1.4;
}

.subtitle {
  font-size: 14px;
  color: #999;
  margin-bottom: 20px;
}

/* 价格信息 */
.price-section {
  padding: 15px 0;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
}

.price-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.price-label {
  font-size: 14px;
  color: #999;
  margin-right: 15px;
}

.price-current {
  font-size: 24px;
  color: #ff5000;
  font-weight: bold;
  margin-right: 10px;
}

.sales-info {
  display: flex;
  font-size: 12px;
  color: #999;
}

.sales-info span:first-child {
  margin-right: 20px;
}

/* 操作按钮 */
.action-buttons {
  padding: 20px 0;
}

.btn-add-cart,
.btn-buy-now {
  height: 48px;
  font-size: 16px;
  padding: 0 30px;
}

.btn-add-cart {
  margin-right: 20px;
}

/* 商品详情区域 */
.detail-section {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

:deep(.detail-tabs .el-tabs__content) {
  padding: 20px;
}

/* 评价区域 */
.comments-container {
  max-height: 600px;
  overflow-y: auto;
  padding-right: 10px;
  /* 添加以下样式来防止横向滚动条 */
  overflow-x: hidden;
  width: 100%;
}

.comment-summary {
  display: flex;
  padding: 20px;
  background-color: #fafafa;
  border-radius: 4px;
  margin-bottom: 20px;
}

.summary-score {
  text-align: center;
  margin-right: 30px;
}

.score {
  display: block;
  font-size: 48px;
  color: #ff5000;
  font-weight: bold;
  line-height: 1;
}

.score-text {
  font-size: 14px;
  color: #999;
}

.summary-detail {
  flex: 1;
  display: flex;
  align-items: center;
}

.comment-count {
  font-size: 16px;
  color: #333;
  font-weight: bold;
}

/* 评价筛选 */
.comment-filter {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.filter-tag {
  cursor: pointer;
}

/* 评价列表 */
.comment-item {
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-header {
  display: flex;
  margin-bottom: 15px;
}

.comment-user-info {
  margin-left: 15px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.user-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 5px;
}

.comment-content {
  font-size: 14px;
  color: #333;
  margin-bottom: 15px;
  line-height: 1.6;
}

.comment-date {
  font-size: 12px;
  color: #999;
}

.comment-product {
  font-size: 12px;
  color: #0e74b8;
}

/* 加载更多 */
.load-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  color: #999;
}

.load-more .el-icon {
  margin-right: 5px;
}

/* 无更多数据 */
.no-more-data {
  text-align: center;
  padding: 20px;
  color: #999;
}

/* 推荐商品 */
.recommend-container {
  max-height: 600px;
  overflow-y: auto;
  padding: 10px 0;
  /* 添加以下样式来防止横向滚动条 */
  overflow-x: hidden;
  width: 100%;
}

.recommend-container :deep(.el-row) {
  margin-left: 0 !important;
  margin-right: 0 !important;
}

.recommend-item {
  cursor: pointer;
  margin-bottom: 20px;
  /* 确保商品项不会超出容器宽度 */
  padding: 0 10px;
  box-sizing: border-box;
}

/* 商品加载更多 */
.load-more-products {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  color: #999;
}

.load-more-products .el-icon {
  margin-right: 5px;
}

/* 无更多商品 */
.no-more-products {
  text-align: center;
  padding: 20px;
  color: #999;
}
</style>